<template>
  <van-cell-group>
    <div v-if="title" class="from-title">
      {{ title }}
    </div>
    <template v-for="(item, index) of FromArr">
      <van-field v-if="+item.type === 1" :key="index" v-model="item.value" :label="item.name" :label-width="labelWidth || '6.2em'"
                 :name="item.name" :placeholder="item.placeholder" :readonly="item.disabled" :required="item.rules?.length === 1"
                 :rules="item.rules" @blur="blur(item)"/>
      <template v-if="+item.type === 2" :key="index">
        <van-field v-model="item.label" :is-link="!item.label" :label="item.name" :label-width="labelWidth || '6.2em'"
                   :name="item.name" :placeholder="item.placeholder" :required="item.rules?.length === 1" :right-icon="item.label ? 'cross' : ''"
                   :rules="item.rules"
                   readonly @blur="blur(item)" @click="!item.disabled ? (item.label ? item.deleteValue(item) || blur(item) : item.showPicker = true) : ''"/>
        <van-popup v-model:show="item.showPicker" position="bottom">
          <van-picker :columns="item.children" :columns-field-names="customFieldName"
                      @cancel="item.showPicker = false" @confirm="(value) => { item.confirm(value, item); blur() }"/>
        </van-popup>
      </template>
      <template v-if="+item.type === 3" :key="index">
        <van-field v-model="item.value" :is-link="!item.value" :label="item.name" :label-width="labelWidth || '6.2em'"
                   :name="item.name" :placeholder="item.placeholder" :disabled="item.disabled" readonly :required="item.rules?.length === 1"
                   :right-icon="item.value ? 'cross' : ''"
                   :rules="item.rules" clickable @blur="blur"
                   @click="!item.disabled ? (item.value ? item.deleteValue(item) || blur(item) : item.showPicker = true) : ''"/>
        <van-popup v-model:show="item.showPicker" position="bottom">
          <van-datetime-picker v-model="item.date" :formatter="formatter" :max-date="maxDate"
                               :min-date="minDate"
                               type="date"
                               @cancel="item.showPicker = false" @confirm="(value) => { item.confirm(value, item); blur(item) }"/>
        </van-popup>
      </template>
      <template v-if="+item.type === 4" :key="index">
        <van-field v-model="item.text" :label="item.name" :label-width="labelWidth || '6.2em'" :placeholder="item.placeholder" :required="item.rules?.length === 1"
                   is-link readonly
                   @click="item.showPicker = true"/>
        <van-popup v-model:show="item.showPicker" position="bottom" round>
          <van-area :area-list="item.children" :title="item.placeholder"
                    @cancel="item.showPicker = false" @confirm="(value) => { item.confirm(value, item); blur(item) }"/>
        </van-popup>
      </template>
      <template v-if="+item.type === 5" :key="index">
        <van-field :label-width="labelWidth || '6.2em'" :placeholder="item.placeholder" :required="item.rules?.length === 1" input-align="center"
                   readonly @click="item.click(item, FromArr)">
          {{ item.name }}
        </van-field>
      </template>
      <template v-if="+item.type === 6" :key="index">
        <van-field v-model="item.placeholder" :label-width="labelWidth || '6.2em'" :required="item.rules?.length === 1" class="submitButton" input-align="center"
                   readonly type="button" @click="go(item)">{{
            item.placeholder
          }}
        </van-field>
      </template>
      <template v-if="+item.type === 8" :key="index">
        <div style="text-align:left;padding:10px 16px">
          <div class="text">{{ item.name + ` (${item.placeholder})` }}</div>
          <van-uploader @click-upload="clickUpload(item.key)" :after-read="afterRead" @oversize="onOversize" v-model="item.value" :max-count="2" multiple @delete="(file)=>fileDelete(file,item)"/>
        </div>
      </template>
      <template v-if="+item.type === 7" :key="index">
        <div style="text-align:left;padding:10px 16px">
          <div class="text">{{ item.name + ` (${item.placeholder})` }}</div>
          <uploader v-model="item.value"/>
        </div>
      </template>
    </template>
  </van-cell-group>
</template>
<script setup>
import {useRouter} from 'vue-router';
import uploader from './uploader.vue'
import {Base64} from 'js-base64'
import {Dialog, Toast} from 'vant'
import {insertSubmitFillInfo} from '@/api/Fillln'
import {useCounterStore} from '../../pinia/user';
import {deleteUploadFile, upload} from "@/api/uploader";


const counterStore = useCounterStore()


const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  FromArr: {
    type: Array,
    default: function () {
      return []
    }
  },
  labelWidth: {
    type: String,
    default: ''
  },
  froKey: {
    type: String,
    default: ''
  }
})


const minDate = new Date(1900, 0, 1)
const maxDate = new Date(2029, 10, 1)


const fileList = ref([]);

// watch(fileList , (value)=>{
//   console.log(value)
// })

onMounted(() => {
  // console.log(FromArr)
})


const router = useRouter()
//此处必须用toRefs，否则将失去响应式
const {FromArr, title, labelWidth, froKey} = toRefs(props);

const customFieldName = {
  text: 'label',
  value: 'value'
}


// 开始调用一次后销毁
function setblur() {
  blur()
}

const orderId = ref(0)
function clickUpload(key){
  orderId.value = key === 'idCardFiles' ? 9 : key === 'bankCardFiles' ? 10 : 0
}


const afterRead = async (file) => {
  const counterStore = useCounterStore()
  const item = {}
  if (!item.employeeId) item.employeeId = counterStore.employeeId
  const id = item.employeeId
  const type = orderId.value
  file.status = 'uploading';
  file.message = '上传中...';
  const formdata = new FormData()
  formdata.append('uploadFile', file.file);
  formdata.append('employeeId', item.employeeId);
  formdata.append('otherId', id);
  formdata.append('type', type);
  const res = await upload(formdata)
  if (res.success) {
    file.status = 'done'
    file.message = '上传成功'
    file.fileName = res.message
  } else {
    file.status = 'failed'
    file.message = res.message
  }
};

const onOversize = (file) => {
  Toast('文件大小不能超过 20MB');
}



async function fileDelete(file,item){
  const type = item.key === 'idCardFiles' ? 9 : item.key ==='bankCardFiles' ? 10 : 0
  const employeeId = counterStore.employeeId
  const otherId = employeeId
  const fileName = file.fileName
  const res = await deleteUploadFile({ fileName, id: employeeId, type, otherId })
  Toast(res.message)
}


watch(FromArr, (value) => {
  if (setblur) {
    setblur()
    setblur = null
  }
})

const formatter = (type, val) => {
  if (type === 'year') return `${val}年`
  if (type === 'month') return `${val}月`;
  if (type === 'day') return `${val}日`;
  return val;
};

const emit = defineEmits(['blur'])
onMounted(() => {

})

const blur = function (item) {
  if (item) item.value = (item.value + '')?.trim()
  const data = {}
  FromArr.value.forEach(it => {
    const value = (it.value + '')?.trim()
    data[it.key] = value
  })
  emit('blur', data, FromArr, froKey)
}
const fromValue = reactive({})

let moduleType = ''
let isFill = ''

const beforeClose = (action) =>
    new Promise((resolve) => {
      if (action === 'confirm') {
        const employeeId = counterStore.employeeId
        const select = document.getElementById('select')
        const index = select.selectedIndex
        const fillIn = select.options[index].value;
        isFill = fillIn === '是' ? '1' : fillIn === '否' ? '2' : ''
        insertSubmitFillInfo({isFill, employeeId, moduleType}).then(res => {
          if (res.success) {
            resolve(true)
          } else {
            Toast.fail(res.message)
          }
        })
      } else if (action === 'cancel') {
        resolve(true)
      }
    });


const go = function (a) {
  const rowKye = a.query.key
  moduleType = rowKye === "education" ? '1' : rowKye === "theTitleTechnicalPost" ? '3' : rowKye === "skill" ? '2' : ''
  Dialog.confirm({
    title: `是否拥有${a.placeholder}`,
    'allow-html': true,
    message: `
      <select name="monh" id="select"  class="select" style="border-radius: 5px; box-sizing: border-box; padding: 10px 15px;  position: absolute;left:0px; width: 50%; margin-left: 50%; transform: translate(-50%, 0); ">
        <option vlaue="1">是</option>
        <option vlaue="2">否</option>
      </select>
    `,
    beforeClose,
  }).then(res => {
    if (+isFill === 1) {
      const query = Base64.encode(JSON.stringify(a.query))
      router.push({
        path: a.url,
        query: {data: query}
      })
    } else if (+isFill === 2) {
      console.log('取消填写')
    }

  })
}

</script>
<style scoped>
.text {
  font-size: var(--van-cell-font-size);
  color: var(--van-field-label-color);
  padding: 10px 16px
}

.from-title {
  background-color: #f7f8fa;
  text-align: left;
  padding: 10px 0;
  /* font-size:14px; */
  color: rgba(15, 18, 20, 0.6);
  font-weight: 600;
}

.submitButton {
  margin: 10px 0;
  border-radius: 12px;
  border: 1px solid #000;
  /* background-color: rgb(88, 239, 1); */
}


.select {
  border-radius: 5px;


}
</style>
